<?php
/**
 * 定义用户排名相关操作
 *
 * @todo
 * @author Judas <judasnow@gmail.com>
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 */

class ranklist_process extends db_obj{
	
	private $db;
	private $db_obj_ranklist;
	private $db_obj_user_judge_statistics;
	
	function __construct( $db ){
		
		$this->db = $db ;
	}
	
	//update_ranklist是否应该放在
	//db_obj_user_judge_statistics
	function update_ranklist(){
		
		$sql = "SELECT username FROM user_judge_statistics ORDER BY accepted_times DESC , submit_times DESC";

		$res = $this->db->query( $sql ); 
		if (PEAR::isError($res)){

			throw new Exception( '更新ranklist出错'.$res->getMessage());
		}

		if ( $res->NumRows() >= 1 ){
			
			//根据返回的结果更新ranklist表
			$db_obj_ranklist = new db_obj_ranklist( $this->db );

			$rank = 1;
			$db_obj_ranklist->reset();

			while ( $row = $res->fetchRow(MDB2_FETCHMODE_ASSOC) ){

				$db_obj_ranklist->set( 'rank' , $rank++ );
				$db_obj_ranklist->set( 'username' , $row['username'] );
				$db_obj_ranklist->save();
			}

		}else{
			
			return false ;	
		}
		
	}

	function get_ranklist(){
		
		$sql = "SELECT ranklist.rank , user_profile.username , user_profile.nick , 
			user_profile.motto , user_judge_statistics.submit_times , 
			user_judge_statistics.accepted_times
			FROM ranklist, user_profile , user_judge_statistics
			WHERE ranklist.username = user_profile.username 
		        AND ranklist.username =	user_judge_statistics.username 
			ORDER BY ranklist.rank";

		$res = $this->db->query( $sql ); 
		if (PEAR::isError($res)) {

			throw new Exception( '获得ranklist出错'.$res->getMessage() );
		}

		if ( $res->NumRows() >= 1 ){
			
			$rows = $res->fetchAll(MDB2_FETCHMODE_ASSOC) ;
			return $rows ;
		
		}else{
			
			return false ;	
		}
	}	
}
